import React, { Component } from 'react'

export default class App extends Component {
  constructor(props) {
    super(props)

    this.state = {
      friends: [
        { name: "张三", age: 18 },
        { name: "李四", age: 30 },
        { name: "王五", age: 21 },
      ]
    }
  }

  render() {
    return (
      <div>
        <h2>好友列表:</h2>
        <ul>
          {
            this.state.friends.map((item, index) => {
              return (
                <li key={index}>
                  名称：{item.name} —— 年龄：{item.age}
                  <button onClick={() => { this.increment(index) }}>+1</button>
                </li>
              )
            })
          }
        </ul>
        <button onClick={() => { this.addMessage() }}>添加数据</button>
      </div>
    )
  }

  increment(index) {
    this.state.friends[index].age += 1
    this.setState({
      friends: this.state.friends
    })
  }

  addMessage() {
    const friend = { name: "新朋友", age: 18 }
    this.state.friends.push(friend)
    this.setState({
      friends: this.state.friends
    })
  }
}
